package com.amt.olcacon;

import com.amt.olcacon.entity.ImpactData;
import com.amt.olcacon.entity.PivotTable;

import java.util.*;
import java.util.stream.Collectors;

public class PivotTableService {
    
    /**
     * 将原始数据转换为透视表
     */
    public PivotTable createPivotTable(List<ImpactData> dataList) {
        Map<String, Map<String, Double>> pivotData = dataList.stream()
                .collect(Collectors.groupingBy(
                    ImpactData::getFlowName,
                    Collectors.toMap(
                        ImpactData::getImpactCategoryName,
                        ImpactData::getResult,
                        (existing, replacement) -> existing // 处理重复键
                    )
                ));
        
        return new PivotTable(pivotData);
    }
    
    /**
     * 获取简化的列名映射（用于显示）
     */
    public Map<String, String> getSimplifiedColumnNames(PivotTable pivotTable) {
        return pivotTable.getColumnNames().stream()
                .collect(Collectors.toMap(
                    name -> name,
                    this::simplifyColumnName
                ));
    }
    
    /**
     * 简化复杂的impact category名称
     */
    private String simplifyColumnName(String fullName) {
        // 定义简化规则
        Map<String, String> rules = new HashMap<>();
        rules.put(".*aircraft emissions.*GWP100.*", "Aircraft_GWP100");
        rules.put(".*biogenic \\(excl\\. CO2\\).*GWP100.*", "Biogenic_GWP100");
        rules.put(".*direct land use change.*GWP100.*", "LandUseChange_GWP100");
        rules.put(".*emissions from direct land use change.*GWP100.*", "Emissions_LandUse_GWP100");
        rules.put(".*fossil - Global warming potential \\(GWP100\\).*", "Fossil_GWP100");
        rules.put(".*fossil emissions \\(excl\\. aircraft emissions\\).*GWP100.*", "Fossil_ExclAircraft_GWP100");
        rules.put(".*removals from direct land use change.*GWP100.*", "Removals_LandUse_GWP100");
        rules.put(".*total \\(excl\\. biogenic CO2\\) - Global warming potential \\(GWP100\\).*", "Total_GWP100");
        rules.put(".*total \\(excl\\. biogenic CO2\\) - Global warming potential \\(GWP20\\).*", "Total_GWP20");
        rules.put(".*total \\(excl\\. biogenic CO2\\) - Global warming potential \\(GWP500\\).*", "Total_GWP500");
        rules.put(".*total \\(excl\\. biogenic CO2\\) - Global temperature change potential \\(GTP50\\).*", "Total_GTP50");
        rules.put(".*total \\(excl\\. biogenic CO2\\) - Global temperature change potential \\(GTP100\\).*", "Total_GTP100");
        rules.put(".*total \\(excl\\. biogenic CO2, incl\\. SLCFs\\).*GWP100.*", "Total_InclSLCFs_GWP100");
        rules.put(".*biogenic \\(excl\\. CO2, incl\\. SLCFs\\).*GWP100.*", "Biogenic_InclSLCFs_GWP100");
        rules.put(".*fossil \\(excl\\. biogenic CO2, incl\\. SLCFs\\).*GWP100.*", "Fossil_InclSLCFs_GWP100");
        rules.put(".*direct land use change \\(incl\\. SLCFs\\).*GWP100.*", "LandUse_InclSLCFs_GWP100");
        
        for (Map.Entry<String, String> rule : rules.entrySet()) {
            if (fullName.matches(rule.getKey())) {
                return rule.getValue();
            }
        }
        
        // 默认简化：取最后一部分
        String[] parts = fullName.split(" - ");
        return parts.length > 1 ? parts[parts.length - 1] : fullName;
    }
    
    /**
     * 按数值大小对行进行排序
     */
    public PivotTable sortRowsByTotal(PivotTable pivotTable, String referenceColumn) {
        Map<String, Double> rowTotals = new HashMap<>();
        
        for (String rowName : pivotTable.getRowNames()) {
            Double value = pivotTable.getValue(rowName, referenceColumn);
            rowTotals.put(rowName, value != null ? value : 0.0);
        }
        
        // 按总值排序
        List<String> sortedRowNames = rowTotals.entrySet().stream()
                .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
        
        // 重新构建透视表数据
        Map<String, Map<String, Double>> sortedData = new LinkedHashMap<>();
        for (String rowName : sortedRowNames) {
            sortedData.put(rowName, pivotTable.getRow(rowName));
        }
        
        return new PivotTable(sortedData);
    }
    
    /**
     * 过滤数据（例如只显示特定类型的impact category）
     */
    public PivotTable filterByColumnPattern(PivotTable pivotTable, String pattern) {
        Map<String, Map<String, Double>> filteredData = new HashMap<>();
        
        for (String rowName : pivotTable.getRowNames()) {
            Map<String, Double> originalRow = pivotTable.getRow(rowName);
            Map<String, Double> filteredRow = originalRow.entrySet().stream()
                    .filter(entry -> entry.getKey().contains(pattern))
                    .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue
                    ));
            
            if (!filteredRow.isEmpty()) {
                filteredData.put(rowName, filteredRow);
            }
        }
        
        return new PivotTable(filteredData);
    }
}